package com.example.medicalzb.service;

import com.example.medicalzb.domain.DrugCompany;
import com.example.medicalzb.entity.DrugCompanyEntity;
import com.example.medicalzb.mapper.CompanyMapper;
import com.example.medicalzb.mapper.CompanyPolicyMapper;
import com.example.medicalzb.util.Msg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CompanyService {
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CompanyPolicyMapper companyPolicyMapper;
    public PageInfo<DrugCompany> getCompanyWithPage(Integer pn, Integer size, String name) {
        if (pn == null){
            pn = 1;
        }
        if (size == null){
            size = Integer.MAX_VALUE;
        }
        if (size == 0){
            size = 1;
        }
        PageHelper.startPage(pn,size);
        List<DrugCompany> list = companyMapper.getAllCompany(name);
        PageInfo<DrugCompany> pageInfo = new PageInfo<>(list,5);
        return pageInfo;
    }

    public Msg getCompanyById(Integer id) {
        DrugCompany drugCompany = companyMapper.getCompanyById(id);
        if (drugCompany != null){
            return Msg.success().data("company",drugCompany);
        }
        return Msg.fail().mess("没有该公司");
    }

    public Msg saveCompany(DrugCompany drugCompany) {
        drugCompany.setCreatetime(new DateTime().toDate());
        drugCompany.setUpdatetime(new DateTime().toDate());
        DrugCompanyEntity drugCompanyEntity = new DrugCompanyEntity();
        BeanUtils.copyProperties(drugCompany,drugCompanyEntity);

        int i = companyMapper.saveCompany(drugCompanyEntity);
        if (i > 0){
            Long num = drugCompanyEntity.getTotal() % 5 == 0 ? (drugCompanyEntity.getTotal() / 5) : ((drugCompanyEntity.getTotal() / 5) + 1);
            return Msg.success().mess("添加公司成功").data("pages",num);
        }
        return Msg.fail().mess("添加公司失败");

    }

    public Msg updateCompany(Long id, DrugCompany drugCompany) {
        drugCompany.setUpdatetime(new DateTime().toDate());
        drugCompany.setCompanyId(id);
        int i = companyMapper.updateCompany(drugCompany);
        if (i > 0){
            return Msg.success().mess("修改公司信息成功");
        }
        return Msg.fail().mess("修改公司信息失败");
    }

    public Msg deleteCompanyById(Integer id) {
        companyPolicyMapper.deletePolicyByCompany(id);
        int i = companyMapper.deleteCompanyById(id);
        if (i > 0){
            return Msg.success().mess("删除公司成功");
        }
        return Msg.fail().mess("删除公司失败");
    }
}
